package com.wn.class30.cotroller.weixin;

import com.wn.class30.entity.*;
import com.wn.class30.mapper.MealPayDao;
import com.wn.class30.mapper.UserCuponDao;
import com.wn.class30.service.IntegralService;
import com.wn.class30.service.UserService;
import com.wn.class30.service.VipService;
import com.wn.class30.tools.MoneyUtils;
import com.wn.class30.tools.Result;
import com.wn.class30.tools.UserIp;
import com.wn.class30.tools.WXPayUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.weixin4j.WeixinException;
import org.weixin4j.model.pay.UnifiedOrder;
import org.weixin4j.model.pay.UnifiedOrderResult;
import org.weixin4j.model.pay.WCPay;
import org.weixin4j.spring.WeixinTemplate;
import org.weixin4j.util.SignUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/weixin")
public class WXBuyVipController {
    @Resource
    private WeixinTemplate weixinTemplate;
    @Resource
    private MealPayDao mealPayDao;
    @Resource
    private IntegralService integralService;
    @Resource
    private UserService userService;
    @Resource
    private VipService vipService;
    @Resource
    private UserCuponDao userCuponDao;

    @RequestMapping(value = "/buyVipPay")
    public Result wxBuyVipPay(HttpServletRequest req,Double Money,String num) throws WeixinException {
        System.out.println(num);
        UnifiedOrder unifiedOrder = new UnifiedOrder();
        unifiedOrder.setAppid(WXPayUtil.APPID);
        unifiedOrder.setMch_id(WXPayUtil.MCHID);
        unifiedOrder.setNonce_str(RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyz"));
        unifiedOrder.setBody("禄舍轩会员充值");
//        String orderIdByTime = UserIp.getOrderIdByTime();
        unifiedOrder.setOut_trade_no(num);
        String s = MoneyUtils.yuanToFen(Money+"");
        unifiedOrder.setTotal_fee(s);
        String ipAddress = UserIp.getIpAddress(req);
        System.out.println(ipAddress);
        unifiedOrder.setSpbill_create_ip(ipAddress);
        String openid = (String) req.getSession().getAttribute("openid");
        unifiedOrder.setOpenid(openid);
        unifiedOrder.setNotify_url(req.getScheme()+"://"+ req.getServerName()+"/weixin/buyVipPayNotify");
        unifiedOrder.setTrade_type("JSAPI");
        Map<String, String> stringStringMap = unifiedOrder.toMap();
        String sign = SignUtil.getSign(stringStringMap, WXPayUtil.PKEY);
        unifiedOrder.setSign(sign);
        //上面为设置微信支付参数
        //下面生成订单
       /* PayOrder payOrder = new PayOrder();
        payOrder.setBussinessId((Integer) req.getSession().getAttribute("wxpaybusinessid"));
        payOrder.setPayMoney(payMoney);
        payOrder.setPayOrderState("0");
        payOrder.setPayUpdateTime(new Date());
        payOrder.setPayOrderNumber(orderIdByTime);
        payOrder.setUserId(useridUtils.queryUseridByOptenid(req));
        wxPayOrderService.insertPayOrder(payOrder);*/
        //下单获取 prepay_id
        UnifiedOrderResult unifiedOrderResult = weixinTemplate.pay().payUnifiedOrder(unifiedOrder);
        String prepay_id = unifiedOrderResult.getPrepay_id();
        //获取 wcPay支付参数
        WCPay wcPay = new WCPay(WXPayUtil.APPID,prepay_id,WXPayUtil.PKEY);

        return new Result("200","sucess",wcPay,null);
    }

    @RequestMapping("/buyVipPayNotify")
    public String callBack(HttpServletRequest request, HttpServletResponse response) {
        //System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        try {
            is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is, "UTF-8");
            System.out.println(xml);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
            if (notifyMap.get("return_code").equals("SUCCESS")) {
                if (notifyMap.get("result_code").equals("SUCCESS")) {
                    String ordersSn = notifyMap.get("out_trade_no");//商户订单号
                    String amountpaid = notifyMap.get("total_fee");//实际支付的订单金额:单位 分
                   /* PayOrder payOrder = wxPayOrderService.queryPayOrderByOrderNum(ordersSn);*/
                    MealPayExample example = new MealPayExample();
                    MealPayExample.Criteria criteria = example.createCriteria();
                    criteria.andVipOrderNumEqualTo(ordersSn);
                    List<MealPay> mealPays = mealPayDao.selectByExample(example);
                    if (mealPays != null && mealPays.size()!=0 && "0".equals(mealPays.get(0).getMealpayStatus())) {
                        MealPay mealPay = mealPays.get(0);
                        mealPay.setMealpayStatus("1");
                        mealPayDao.updateByPrimaryKeySelective(mealPay);

                        List<Map<String,Object>> mealAndVip = userService.selectMealAndVip(mealPay.getMealId());
                        System.out.println("mealAndVip:"+mealAndVip);
                        //查询用户信息
                        User user1 = userService.queryUserByUderid(mealPay.getUserid());
                        userService.updateUserByMealAndVip(user1.getUserId(),mealAndVip.get(0));
                        UserCupon uc = new UserCupon();
                        uc.setUserId(mealPay.getUserid());
                        uc.setCuponId(2);
                        uc.setCuponNum(3);
                        uc.setCuponGettime(new Date());
                        userCuponDao.insert(uc);

                    }

                }
            }
            //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
            is.close();
        } catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }


}
